package com.baizhi.realm;

import com.baizhi.dao.AdminDAO;
import com.baizhi.entity.Admin;
import com.baizhi.service.ResourceService;
import com.baizhi.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {

    @Autowired
    private AdminDAO adminDAO;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;

    /**
     * 获取授权信息
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        1、获取用户名，主身份信息
        String principal = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("principal = " + principal);
//        2、根据用户名查询角色信息和权限信息
        Set<String> role = roleService.showByName(principal);
        Set<String> permissions = resourceService.showByName(principal);

//        3、封装info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(role);
        info.setStringPermissions(permissions);

        return info;
    }

    /**
     * 获取认证信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();

        Admin admin = adminDAO.selectByUsername(username);

        if (admin != null){
            return new SimpleAuthenticationInfo(admin.getUsername(),admin.getPassword(),this.getName());
        }


        return null;
    }
}
